﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tools
{
    public static class ListHelper
    {
        /// <summary>
        /// 获取数组随机N个元素
        /// </summary>
        /// <param name="array">指定数组</param>
        /// <param name="count">获取元素个数</param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T[] GetRandomChild<T>(this T[] array, int count)
        {
            var tempArray = new T[array.Length];
            var tempResultArray = new T[count];
            array.CopyTo(tempArray, 0);
            tempArray.SortRandom();
            Array.Copy(tempArray, tempResultArray, count);
            return tempResultArray;
        }

        /// <summary>
        /// 获取列表随机N个元素
        /// </summary>
        /// <param name="list"></param>
        /// <param name="count"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> GetRandomChild<T>(this List<T> list, int count)
        {
            var tempList = new List<T>();
            // tempList = list.GetRange(0,list.Count);
            tempList.AddRange(list);
            tempList.SortRandom();
            return tempList.GetRange(0, count);
        }

        /// <summary>
        /// 数组的2个元素位置调换
        /// </summary>
        public static void Swap<T>(this T[] array, int index1, int index2)
        {
            var temp = array[index2];
            array[index2] = array[index1];
            array[index1] = temp;
        }
        /// <summary>
        /// 列表的2个元素位置调换
        /// </summary>
        public static void Swap<T>(this List<T> list, int index1, int index2)
        {
            var temp = list[index2];
            list[index2] = list[index1];
            list[index1] = temp;
        }

        /// <summary>
        /// 乱序排序数组
        /// </summary>
        public static T[] SortRandom<T>(this T[] array)
        {
            var list = array.ToList().SortRandom();
            return list.ToArray();
        }
        /// <summary>
        /// 乱序排序列表
        /// </summary>
        public static List<T> SortRandom<T>(this List<T> list)
        {
            var random = new Random();
            var newList = new List<T>();
            foreach (var item in list)
            {
                newList.Insert(random.Next(newList.Count + 1), item);
            }
            return newList;
        }
    }
}
